package com.yjd.pub.tag.service;

import com.yjd.comm.base.dao.IBaseDao;
import com.yjd.comm.base.service.impl.BaseServiceImpl;
import com.yjd.comm.enums.ReferenceTypeEnum;
import com.yjd.comm.tag.model.TagRelevanceModel;
import com.yjd.comm.tag.service.ITagRelevanceService;
import com.yjd.comm.util.FrameUtil;
import com.yjd.pub.tag.dao.ITagRelevanceDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <b>description</b>：标签关联业务实现<br>
 * <b>time</b>：2017-06-27 08:58:34 <br>
 * <b>author</b>：  yangchangyan@yijiedai.com
 */
@Service("tagRelevanceService")
public class TagRelevanceServiceImpl extends BaseServiceImpl implements ITagRelevanceService {

	/**
	 * 插入
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public TagRelevanceModel insert(TagRelevanceModel model) throws Exception {
		return this.tagRelevanceDao.insertModel(model, true);
	}

	/**
	 * 更新
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public int update(TagRelevanceModel model) throws Exception {
		return this.tagRelevanceDao.updateModel(model, true);
	}

	/**
	 * 根据id删除
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public int delete(long id) throws Exception {
		Map<Object, Object> paramMap = new HashMap<Object, Object>();
		paramMap.put("id", id);
		return this.tagRelevanceDao.deleteModel(paramMap, true);
	}

	/**
	 * 批量新增
	 *
	 * @param list
	 * @throws Exception
	 */
	@Override
	public void batchInsert(List<TagRelevanceModel> list,Long prj_id) throws Exception {
		if(prj_id==null){
			FrameUtil.throwBaseException1("请求参数异常");
		}
		this.tagRelevanceDao.deleteTagRelevance(FrameUtil.newHashMap("ref_type",2,"ref_id",prj_id));
		this.tagRelevanceDao.insertBatch(list,true);
	}

	@Override
	public void updateTagRelevance(String[] tags, Long ref_id, ReferenceTypeEnum ref_type) throws Exception {
		if(null == tags && tags.length == 0){
			return;
		}

		Long currentTime = FrameUtil.getTime();
		List<TagRelevanceModel> tagRelevanceModelList = new ArrayList<TagRelevanceModel>();
		for(String tag :tags){

			TagRelevanceModel tagRelevanceModel = new TagRelevanceModel();
			tagRelevanceModel.setRef_type(ref_type.getCode());
			tagRelevanceModel.setTag_id(Long.parseLong(tag));
			tagRelevanceModel.setCreate_time(currentTime);
			tagRelevanceModel.setLast_update_time(currentTime);
			tagRelevanceModel.setSort(0);
			tagRelevanceModel.setRef_id( ref_id);
			tagRelevanceModelList.add(tagRelevanceModel);
		}
		this.tagRelevanceDao.deleteTagRelevance(FrameUtil.newHashMap("ref_type", ref_type.getCode(), "ref_id", ref_id));
		this.tagRelevanceDao.insertBatch(tagRelevanceModelList,true);
	}

	@Resource
	private ITagRelevanceDao tagRelevanceDao;

	@Override
	public IBaseDao getBaseDao() {
		return this.tagRelevanceDao;
	}

}
